//
//  WmcPreViewVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/24.
//

import UIKit
import YPBedrock

// MARK: - 扩展WmcMediaBrowseVC + WmcNavigatorProtocol

extension WmcMediaBrowseVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.imageBrowse]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcMediaBrowseVM()
        if let viewModel = parms.context as? WmcMediaBrowseVM {
            vm = viewModel
        }
        let vc = WmcMediaBrowseVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcMediaBrowseVC + WmcVMProtocol

extension WmcMediaBrowseVC: WmcVMProtocol {
    typealias VMType = WmcMediaBrowseVM
}

// MARK: - [WmcMediaBrowseVC]

open class WmcMediaBrowseVC: WmcBaseVC {
    // Lifecycle

    override open func viewDidLoad() {
        super.viewDidLoad()

        // 刷新工具栏按钮
        YPWmcManager.shared.drivingManager.mediaBrowse_reloadToolMenuItemsBlock = { [weak self] mediaType in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadMenuListData(mediaType: mediaType)
        }

        // 添加气泡
        YPWmcManager.shared.drivingManager.mediaBrowse_addTooMenuPopBlock = { [weak self] model, index in
            guard let weakSelf = self else { return }
            weakSelf.addPopView(model, at: index)
        }
    }

    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 本地相册无图片返回
        switch viewModel.albumType {
        case .local:
            // 如果图片空，则返回
            if viewModel.mediaList.count <= 0 {
                backAction()
            }
        default: break
        }

        var isShowGuide: Bool = false
        if let isShowGuideCache: Bool = WmcUserdefault.object(forKey: .Tips.PhotoBrowser.uploadGuide) {
            isShowGuide = isShowGuideCache
        }
        toolView.uploadRedPoint.isHidden = isShowGuide
    }

    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        preView.stopPlay()
    }

    // Internal

    static var TooBarHeight: CGFloat { Wmc_safeAreaBottom + 65 }

    lazy var allPhotoBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("所有照片", for: .normal)
        btn.setTitleColor(.wmc_mainTheme, for: .normal)
        btn.titleLabel?.font = 16.yp.uiFont(weight: .medium)
        return btn
    }()

    lazy var imageCountLabel: UILabel = {
        let label = UILabel.YP.Create(font: 16.yp.uiFont(weight: .medium),
                                      color: UIColor.wmc_grayH2_323233,
                                      alignment: .right)
        return label
    }()

    lazy var toolView: WmcMediaBrowseToolView = {
        let view = WmcMediaBrowseToolView()
        return view
    }()

    lazy var preView: WmcMediaBrowsePreviewView = {
        let view = WmcMediaBrowsePreviewView(mediaList: viewModel.mediaList,
                                             albumType: viewModel.albumType,
                                             showIndex: viewModel.showIndex)
        return view
    }()

    /// 照片浏览代理
    var photoBrowseDelegate: WmcMediaBrowseDelegate? {
        return YPWmcManager.shared.uiDelegate.mediaBrowseDelegate
    }

    override func backAction() {
        popVC(style: viewModel.backStyle)
    }

    override func bindDriving() {
        YPWmcDrivingManager.shared.mediaBrowse_currentMediaWatermarkBlock = { [weak self] in
            guard let weakSelf = self else { return nil }
            return weakSelf.viewModel.currentMediaWatermarkBlock?(weakSelf.preView.currentIndex)
        }
    }

    override func makeUI() {
        makeNavView(showShadow: false)
        // 左上角
        switch viewModel.topLeftStyle {
        case .close: // 关闭
            navViewSetCloseImage()
        case let .closeTitle(title: title): // 关闭带标题
            navViewSetCloseImage()
            self.title = title
        case .back: // 返回
            self.title = nil
        case let .backTitle(title: title): // 返回带标题
            self.title = title
        }

        // 右上角
        switch viewModel.topRightStyle {
        case .none: // 无
            break
        case .imageCount: // 图片计数
            navView.addSubview(imageCountLabel)
            imageCountLabel.snp.makeConstraints { make in
                make.centerY.height.equalTo(navView.backImageView)
                make.right.equalTo(-Wmc_standardEdge.right)
            }
        case .allPhoto: // 所有照片
            navView.addSubview(allPhotoBtn)
            allPhotoBtn.snp.makeConstraints { make in
                make.centerY.height.equalTo(navView.backImageView)
                make.right.equalTo(-Wmc_standardEdge.right)
            }
        }

        addSubview(toolView)
        toolView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(Self.TooBarHeight)
        }

        addSubview(preView)
        preView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(toolView.snp.top)
        }
    }

    /// 过滤媒体类型
    func filterDBModelMediaType(_ list: [WmcLocalMediaAlbumDBManager.DBModel]) -> [WmcLocalMediaAlbumDBManager.DBModel] {
        var defaultTypes: [WmcMedia.MediaType] = [.image, .video]
        if let localAlbumDelegate = YPWmcManager.shared.uiDelegate.localAlbumDelegate {
            defaultTypes = localAlbumDelegate.loadMediaType(.current, defaultMediaTypes: defaultTypes)
        }
        var newList: [WmcLocalMediaAlbumDBManager.DBModel] = []
        for media in list {
            if defaultTypes.contains(media.mediaType) { // 包含类型
                newList.append(media)
            }
        }
        return newList
    }
    
    override func bindViewAction() {
        // 右上角所有照片
        allPhotoBtn.yp.addEvent() { _ in
            let vm = WmcLocalAlbumVM()
            vm.backMediaBlock = { [weak self] mediaList, dbList in
                WmcLocalMediaAlbumDBManager.searchMediaData(page: 1, pageSize: 50) { [weak self] list in
                    guard let weakSelf = self else { return }
                    let newList = weakSelf.filterDBModelMediaType(list)
                    // 回调数据刷新
                    var mediaList: [WmcMedia] = []
                    newList.forEach { dbModel in
                        if let filePath = dbModel.mediaInfoType.filePath {
                            switch dbModel.mediaType {
                            case .image:
                                mediaList.append(WmcImage(filePath: filePath))
                            case .video:
                                mediaList.append(WmcVideo(filePath: filePath))
                            default: break
                            }
                        }
                    }
                    weakSelf.viewModel.mediaList = mediaList
                    weakSelf.viewModel.dataSourceList = dbList
                }
            }
            WmcNavigatorManager.push(.localAlbum, style: .bottom, parms: vm)
        }

        
        
        // 编辑
        toolView.editBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self,
                  let wmcImage = weakSelf.preView.currentMedia as? WmcImage else { return }
            // 加载出图片
            wmcImage.loadUIImage { image in
                let vm = WmcEditPhotoVM()
                vm.inputImage = image
                WmcNavigatorManager.push(.editPhoto, style: .alpha, parms: vm)
            }
        }
        // 删除
        toolView.deleteBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            let index = weakSelf.preView.currentIndex
            weakSelf.viewModel.actionFunction(.delete, index: index)
        }

        // 上传云相册
        toolView.uploadBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            /// 检查是否登录
            let index = weakSelf.preView.currentIndex
            weakSelf.viewModel.actionFunction(.upload, index: index)

            WmcUserdefault.save(value: true, forKey: .Tips.PhotoBrowser.uploadGuide)
            weakSelf.toolView.uploadRedPoint.isHidden = true
        }

        // 分享
        toolView.sharedBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            switch weakSelf.viewModel.shareMode {
            case .default: // 默认分享

                guard let wmcMedia = weakSelf.preView.currentMedia else { return }
                let shareAlertView = WmcShareAlertView()
                let sharedConfig: WmcShareAlertView.ShareType.Config = .init()
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    wmcImage.loadUIImage { [weak self] image in
                        guard let weakSelf = self else { return }
                        shareAlertView.shareType = .image(image, config: sharedConfig)
                        weakSelf.showShareView(shareAlertView)
                    }
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    switch wmcVideo.videoType {
                    case let .filePath(path): // 地址
                        shareAlertView.shareType = .file(path, fileExtension: "mp4", config: sharedConfig)

                    case let .url(url): // 链接
                        let path = URL.YP.Create(url).absoluteString
                        if path.hasPrefix("file:///") { // 文件
                            let newPath = path.yp.removeFileUrlPrefix()
                            shareAlertView.shareType = .file(newPath, fileExtension: "mp4", config: sharedConfig)
                        } else {
                            shareAlertView.shareType = .link(path, config: sharedConfig)
                        }
                    default: break
                    }
                    weakSelf.showShareView(shareAlertView)
                } else { // 其他
                    WmcHudManager.toast("未知媒体！")
                }

            case .custom: // 自定义外调
                let index = weakSelf.preView.currentIndex
                weakSelf.viewModel.actionFunction(.share, index: index)
            }
        }

        // 朋友圈
        toolView.friendsCircleBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            switch weakSelf.viewModel.shareFriendsCircleMode {
            case .default: // 默认分享

                guard let wmcMedia = weakSelf.preView.currentMedia else { return }
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .friendCircle)
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    weakSelf.shared(video: wmcVideo, scene: .friendCircle)
                } else { // 其他
                    WmcHudManager.toast("未知媒体！")
                }

            case .custom: // 自定义外调
                let index = weakSelf.preView.currentIndex
                weakSelf.viewModel.actionFunction(.shareFriendsCircle, index: index)
            }
        }

        // 微信好友
        toolView.wechatBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            switch weakSelf.viewModel.shareWechatMode {
            case .default: // 默认分享

                guard let wmcMedia = weakSelf.preView.currentMedia else { return }
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .session)
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    weakSelf.shared(video: wmcVideo, scene: .session)
                } else { // 其他
                    WmcHudManager.toast("未知媒体！")
                }

            case .custom: // 自定义外调
                let index = weakSelf.preView.currentIndex
                weakSelf.viewModel.actionFunction(.shareWechat, index: index)
            }
        }

        // 保存
        toolView.saveBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            let index = weakSelf.preView.currentIndex
            weakSelf.viewModel.actionFunction(.save, index: index)
        }

        // 预览图滑动回调
        preView.browseDidScrollBlock = { [weak self] index, media in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadMenuListData(mediaType: media.mediaType())
            weakSelf.updateImageCount(currentIndex: index)
            weakSelf.viewModel.currentIndex = index
            
            // 外部事务回调
            YPWmcManager.shared.uiDelegate.mediaBrowseDelegate?
                .browseScrollDidScroll(.current,
                                       albumType: weakSelf.viewModel.albumType,
                                       currentMedia: media,
                                       collectionView: weakSelf.preView)
            // 为了回调水印信息
            if let dataSourceList = weakSelf.viewModel.dataSourceList,
               let dbModel = dataSourceList.yp.object(at: index) {
                let waterMarkModel = WmcWatermarkDetailModel.deserialize(from: dbModel.mediaInfoType.watermarkJson)
                let saveTime = dbModel.saveTime
                YPWmcManager.shared.uiDelegate.mediaBrowseDelegate?
                    .browseScrollDidScroll(.current,
                                           albumType: weakSelf.viewModel.albumType,
                                           currentMedia: media,
                                           watermarkModel: waterMarkModel,
                                           saveTime: saveTime,
                                           collectionView: weakSelf.preView)
            }
        }
    }

    /// 更新左上角数字
    func updateImageCount(currentIndex: Int) {
        guard let _ = imageCountLabel.superview else { return }
        let totalCount = viewModel.mediaList.count
        imageCountLabel.text = "\(currentIndex + 1) / \(totalCount)"
    }

    override func bindViewModel() {
        // 媒体数组更新
        viewModel.mediaListUpdateRelay.subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.preView.mediaList = list
        }).disposed(by: rx.disposeBag)

        // 删除空了回调
        viewModel.mediaListEmptyRelay.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.backAction()
        }).disposed(by: rx.disposeBag)

        // 订阅底部按钮发生变化
        viewModel.toolMenuListRelay.subscribe(onNext: { [weak self] list, mediaType in
            guard let weakSelf = self else { return }
            weakSelf.toolView.reloadToolMenuData(menuList: list,
                                                 albumType: weakSelf.viewModel.albumType,
                                                 mediaType: mediaType)
        }).disposed(by: rx.disposeBag)
    }

    /// 分享图片
    func shared(image: WmcImage?, scene: WmcShareManager.Scene) {
        guard let wmcImage = image else { return }
        wmcImage.loadUIImage { image in
            WmcShareManager.shareImage(image, scene: scene)
        }
    }

    /// 分享视频
    func shared(video: WmcVideo?, scene: WmcShareManager.Scene) {
        guard let wmcVideo = video else { return }
        switch wmcVideo.videoType {
        case let .filePath(path): // 地址
            WmcShareManager.shareFile(path, fileExtension: "mp4", title: "", scene: scene)

        case let .url(url): // 链接
            let path = URL.YP.Create(url).absoluteString
            if path.hasPrefix("file:///") { // 文件
                let newPath = path.yp.removeFileUrlPrefix()
                WmcShareManager.shareFile(newPath, fileExtension: "mp4", title: "", scene: scene)
            } else {
                WmcShareManager.shareLink(path, title: "", scene: scene)
            }
        default: break
        }
    }

    /// 展示气泡视图
    func addPopView(_ model: WmcBubbleVM, at index: Int) {
        guard let markView = toolView.stackView.arrangedSubviews.yp.object(at: index) else { return }
        let bubbleVM = model
        bubbleVM.markView = markView
        bubbleVM.showInView = view
        let bubbleView = WmcBubbleView(bubbleVM)
        bubbleView.show()
    }

    /// 显示分享视图
    func showShareView(_ shareAlertView: WmcShareAlertView) {
        let height = Wmc_safeAreaBottom + 214
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(height)
        }))
        presentVC.show()
    }

    // Private

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("已保存到系统相册")
        }
    }
}
